package com.jtoon.servlet;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jtoon.bean.Comics;
import com.jtoon.bean.User;
import com.jtoon.util.PMF;

public class Join extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		RequestDispatcher rd = request.getRequestDispatcher("/page/join.jsp"); 
		rd.forward(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		boolean error = false;
		String msg = "";
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");
		String pwc = request.getParameter("pwc");
		  
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(User.class);
		
		try{
			
			query.setFilter("uid == uidParam");
			query.declareParameters("String uidParam");
			List<User> isUser = (List<User>)query.execute(id);
			
			if(id == null || id.equals("")){
				error = true;
				msg = "아이디를 입력하세요.";
			}else if(pw == null || pw.equals("")){
				error = true;
				msg = "비밀번호를 입력하세요.";
			}else if(pwc == null || pwc.equals("")){
				error = true;
				msg = "비밀번호확인을 입력하세요.";
			}else if(!pw.equals(pwc)){
				error = true;
				msg = "비밀번호와 비밀번호확인이 일치하지 않습니다.";
			}else if(0 < isUser.size()){
				error = true;
				msg = "동일한 아이디가 존재합니다.";
			}
			
			if(!error){
				User newUser = new User(id, pw);
				pm.makePersistent(newUser); 
				RequestDispatcher rd = request.getRequestDispatcher("/page/join_complete.jsp"); 
				rd.forward(request, response);
			}else{
				RequestDispatcher rd = request.getRequestDispatcher("/page/join.jsp"); 
				request.setAttribute("msg", msg);
				rd.forward(request, response);
			}
			    
		}finally{
			pm.close();
		}
		
	}
	
}
